package horncomb.bpm.task;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import horncomb.bpm.process.core.ExecutionContext;
import horncomb.bpm.process.core.Transition;

/**
 * @author Daniel
 */
public class AutoNextTransitionStrategy implements NextTransitionStrategy {
	@SuppressWarnings("unchecked")
	public Transition getNextTransition(ExecutionContext context) {
		if (context.getContextModel() != null) {
			if ((context.getContextModel()) instanceof Transition) {
				return (Transition) context.getContextModel();
			} else if ((context.getContextModel()) instanceof NextTransitionHolder) {
				return this.doGetTransition(context,
						(NextTransitionHolder) context.getContextModel());
			} else if (context.getContextModel().getClass().isArray()) {
				return this.doGetTransitionInCollection(context,
						CollectionUtils.arrayToList(context.getContextModel()));
			} else if (context.getContextModel() instanceof Collection) {
				return this.doGetTransitionInCollection(context,
						((Collection) context.getContextModel()));
			} else if (context.getContextModel() instanceof Map) {
				return this.doGetTransitionInCollection(context, ((Map) context
						.getContextModel()).values());
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private Transition doGetTransitionInCollection(ExecutionContext context,
			Collection c) {
		Iterator i = c.iterator();
		while (i.hasNext()) {
			if (i.next() instanceof NextTransitionHolder) {
				return this.doGetTransition(context, (NextTransitionHolder) i
						.next());
			}
		}
		return null;
	}

	private Transition doGetTransition(ExecutionContext context,
			NextTransitionHolder holder) {
		return context.getToken().getState().getProcessDefinition()
				.findTransition(holder.getNextTransitionId());
	}
}
